package com.yesin.goods.service;

import com.yesin.goods.client.BrandClient;
import com.yesin.goods.client.CategoryClient;
import com.yesin.goods.client.GoodsClient;
import com.yesin.goods.client.SpecificationClient;
import com.yesin.item.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class GoodsService {

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private BrandClient brandClient;

    @Autowired
    private SpecificationClient specificationClient;

    public Map<String, Object> loadData(Long id) {
        Map<String, Object> modelMap = new HashMap<>();
        Spu spu = this.goodsClient.querySpuById(id);
        // 根据spuId查询分类
        List<Long> cIds = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
        List<String> names = this.categoryClient.queryNamesByIds(cIds);
        List<Map<String, Object>> categories = new ArrayList<>();
        for (int i = 0; i < cIds.size(); i++){
            Map<String, Object> categoryMap = new HashMap<>();
            categoryMap.put("id", cIds.get(i));
            categoryMap.put("name", names.get(i));
            categories.add(categoryMap);
        }
        // 查询spu对应的品牌
        Brand brand = this.brandClient.queryBrandById(spu.getBrandId());
        // 根据spuId查询SKU集合
        List<Sku> skus = this.goodsClient.querySkuListBySpuId(id);
        // 根据spuId查询商品详情
        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(id);
        // 根据分类查询参数分组
        List<SpecGroup> groups = this.specificationClient.queryGroupsByCid(spu.getCid3());
        // 查询特殊规格参数
        List<SpecParam> params = this.specificationClient
                .queryParams(null, spu.getCid3(), false, null);
        Map<Long, String> paramMap = new HashMap<>();
        params.forEach(param ->
            paramMap.put(param.getId(), param.getName()));
        modelMap.put("spu", spu);
        modelMap.put("categories", categories);
        modelMap.put("brand", brand);
        modelMap.put("skus", skus);
        modelMap.put("spuDetail", spuDetail);
        modelMap.put("groups", groups);
        modelMap.put("paramMap", paramMap);

        return modelMap;
    }
}
